package com.smile.frame.workflow.flowable.demo.config;

import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.ProcessEngineConfigurationConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncListenableTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.List;

/**
 * BPM 模块的 Flowable 配置类
 *
 * @author jason
 */
@Configuration(proxyBeanMethods = false)
//public class BpmFlowableConfiguration {
public class BpmFlowableConfiguration implements ProcessEngineConfigurationConfigurer {
    @Autowired
    private List<FlowableEventListener> flowableEventListeners;

    /**
     * 参考 {@link org.flowable.spring.boot.FlowableJobConfiguration} 类，创建对应的 AsyncListenableTaskExecutor Bean
     * <p>
     * 如果不创建，会导致项目启动时，Flowable 报错的问题
     */
    @Bean(name = "applicationTaskExecutor")
    @ConditionalOnMissingBean(name = "applicationTaskExecutor")
    public AsyncListenableTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(8);
        executor.setMaxPoolSize(8);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("flowable-task-Executor-");
        executor.setAwaitTerminationSeconds(30);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAllowCoreThreadTimeOut(true);
        executor.initialize();
        return executor;
    }
//
//    /**
//     * BPM 模块的 ProcessEngineConfigurationConfigurer 实现类：
//     * <p>
//     * 1. 设置各种监听器
//     * 2. 设置自定义的 DefaultActivityBehaviorFactory 实现
//     */
//    @Bean
//    public EngineConfigurationConfigurer<SpringProcessEngineConfiguration> bpmProcessEngineConfigurationConfigurer(
//            ObjectProvider<FlowableEventListener> listeners
//    ) {
//        return configuration -> {
//            // 注册监听器，例如说 BpmTaskEventListener
//            configuration.setEventListeners(ListUtil.toList(listeners.iterator()));
//        };
//    }


    @Override
    public void configure(SpringProcessEngineConfiguration engineConfiguration) {
        // 注册监听器
        engineConfiguration.setEventListeners(flowableEventListeners);
    }
}